<template>
  <List v-if="showList" ref="list" class="product" component-name="NavFilter" :set-page-size="10" :finished.sync="finished" :reset-fun="resetData" :load="load" :refresh="load">
    <ShowWindow
      v-for="(g,i) in list"
      :key="i"
      is-product
      :name="g.productName"
      :price="g.price"
      :src="g.pic"
      :tag-list="getSellingPoints(g)"
      @click="clickHandle(g)"
    />
  </List>
</template>
<script>
import ShowWindow from '@/components/ShowWindow'
import List from '@/components/List'
import { gcenterProduct, getDefaultTemplateIdfunction } from '@/apis/search'
import { randomId } from '@/utils'
import { mapGetters, mapMutations } from 'vuex'

export default {
  name: 'Product',
  components: {
    ShowWindow,
    List
  },
  refresh: true,
  props: {
    searchValue: {
      type: String,
      default: ''
    },
    skuCodes: {
      type: Array,
      default: () => []
    },
    isCustomSpu: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      list: [],
      finished: false,
      defaultTemplateId: '',
      rawFilterData: [],
      keyword: '',
      attr_ev: ''
    }
  },
  computed: {
    ...mapGetters('nav', ['filterData', 'selectList']),
    gotoValue() {
      return this.$route.query.value || ''
    },
    defaultCategoryIds() {
      const ids = this.$route.query.categoryIds || ''
      if (ids && ids.length > 0) {
        return ids.split('_')
      }
      return []
    },
    isSearch() {
      return this.$route.name === 'SearchProduct'
    },
    showList() {
      if (this.isCustomSpu) {
        return this.skuCodes.length > 0
      }
      return true
    }
  },
  watch: {

  },
  created() {
    this.$on('refresh', this.resetPageData)
  },
  activated() {
    this.updateFilterData(this.rawFilterData)
  },
  methods: {
    ...mapMutations('nav', ['updateFilterData']),
    resetPageData(v, type) {
      if (v === 'confirm') {
        // return
      }
      // if (/^attr@@@.*/.test(v)) return
      if (type === 'serarch_string') {
        this.attr_ev = ''
      } else if (type === 'serarch_attr') {
        this.attr_ev = v
      }
      if (this.$refs.list) {
        this.$refs.list.resetPageData()
      }
    },
    async load(page, rows) {
      let defaultTemplateId
      if (this.isSearch || this.isCustomSpu) {
        if (this.isCustomSpu) {
          if (!this.skuCodes || this.skuCodes.length === 0) {
            return Promise.reject(null)
          }
        } else {
          if (this.searchValue === '' && this.attr_ev === '') {
            return Promise.reject(null)
          }
        }
        if (!this.defaultTemplateId) {
          await this.getTemplate()
          defaultTemplateId = this.defaultTemplateId
        } else {
          defaultTemplateId = this.defaultTemplateId
        }
      } else {
        defaultTemplateId = this.gotoValue
      }
      if (!defaultTemplateId) return Promise.reject('noError')
      const selectedData = this.$extrFilterData(this.filterData)
      const c1Ids = this.$extrFIlterValueByFlag(selectedData, /^c1@@@.*/, false)
      const c2Ids = this.$extrFIlterValueByFlag(selectedData, /^c2@@@.*/, false)
      const c3Ids = this.$extrFIlterValueByFlag(selectedData, /^c3@@@.*/, false)
      const c4Ids = this.$extrFIlterValueByFlag(selectedData, /^c4@@@.*/, false)
      const categoryIds = this.$extrFIlterValueByFlag(selectedData, /^category@@@.*/, false)
      let attr = this.$extrFIlterEvsValueByFlag(selectedData, /^attr@@@.*/, true, '@')
      const templateEv = this.$extrFIlterEvsValueByFlag(selectedData, /^template_attr@@@.*/, true, '@')
      const productStates = this.$extrFIlterValueByFlag(selectedData, /^product_state@@@.*/, false)
      const purchaseHandles = this.$extrFIlterValueByFlag(selectedData, /^purchase_handle@@@.*/, false)
      let defaultCategoryIds = []
      // 搜索和自定义页面spu商品页不需要默认分类
      if (!this.isSearch && this.skuCodes.length === 0) {
        defaultCategoryIds = this.defaultCategoryIds
      }
      let isDefaultFilterCondition = 'Y'
      if (selectedData.length > 0 || this.searchValue !== '') {
        isDefaultFilterCondition = 'N'
      }
      if (this.attr_ev) {
        if (selectedData.length === 0) {
          isDefaultFilterCondition = 'Y'
        }
      }
      if (isDefaultFilterCondition === 'N' && this.filterData.length === 0) {
        // 筛选项不存在时，默认筛选条件为Y，解决初次查询(因未带默认条件查询)与二次查询结果不一致的问题
        isDefaultFilterCondition = 'Y'
      }
      // 搜索参数
      let keyword = this.searchValue
      if (this.attr_ev) {
        attr = [attr, this.attr_ev].filter(e => e).join('@')
        keyword = ''
      }

      let sort = this.$extrFIlterValueByFlag(selectedData, /^sort*/, false).join(',')

      const data = {
        page,
        rows,
        c1Ids,
        c2Ids,
        c3Ids,
        c4Ids,
        categoryIds,
        defaultCategoryIds,
        productStates,
        purchaseHandles,
        keyword,
        isDefaultFilterCondition,
        filterTemplateConditionId: defaultTemplateId,
        ev: attr,
        templateEv,
        skuCodes: this.skuCodes
        // categoryIds: []
      }
      if (!this.isSearch) {
        if (!sort) {
          sort = 'sort_ttm_desc'
        }
      }
      if (sort && sort !== 'default') {
        data.sort = sort
      }

      const priceRange = this.filterData.find(v => v.flag === 'price')
      if (priceRange) {
        if (priceRange.rawValue1) {
          data.priceFrom = priceRange.rawValue1
        }
        if (priceRange.rawValue2) {
          data.priceTo = priceRange.rawValue2
        }
      }

      const dateRange = this.filterData.find(v => v.flag === 'ttm')
      if (dateRange) {
        if (dateRange.rawValue1) {
          data.ttmFrom = `${dateRange.rawValue1}`
        }
        if (dateRange.rawValue2) {
          data.ttmTo = `${dateRange.rawValue2}`
        }
      }

      const routeName = this.$route.name
      if (page === 1) this.list = []
      return gcenterProduct(data).then(res => {
        if (page === 1) this.list = []
        const data = (res.data && res.data.remoteSolrProductGroupDTOS) || ''
        if (data && data.records) {
          this.list.push(...data.records)
        }

        if (!data || !(data.records && data.records.length) || (data.totalRows <= this.list.length)) {
          this.finished = true
        }
        if (!data) return

        const filterData = res.data.filterData
        this.$concatFilterData(filterData, this.filterData)

        if (this.$route.name === routeName) {
          const sortPriceRaw = [
            {
              unId: randomId(),
              title: '排序',
              show: true,
              flag: 'sort',
              type: 'priceSort',
              multiple: false,
              isMultChoose: false,
              children: [
                { label: '默认排序', value: 'default', selected: !['sort_price_desc', 'sort_price_asc', 'sort_ttm_desc'].includes(sort) },
                { label: '新品优先', value: 'sort_ttm_desc', selected: sort === 'sort_ttm_desc' },
                // { label: '新品优先', value: 'sort_ttm_asc', selected: sort === 'sort_ttm_asc' }, // 上市时间从低到高
                { label: '价格从低到高', value: 'sort_price_asc', selected: sort === 'sort_price_asc' },
                { label: '价格从高到低', value: 'sort_price_desc', selected: sort === 'sort_price_desc' }
              ]
            },
            {
              uuId: randomId(),
              title: '价格范围',
              flag: 'price',
              show: false,
              type: 'textrange',
              selected: true,
              value1: priceRange?.rawValue1 || '',
              value2: priceRange?.rawValue2 || '',
              rawValue1: priceRange?.rawValue1 || '',
              rawValue2: priceRange?.rawValue2 || '',
              placeholder1: '最低价',
              placeholder2: '最高价',
              fieldType: 'number',
              formatter: (value) => {
                if (['', null, undefined].includes(value)) return ''
                var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
                if (!reg.test(value)) {
                  this.$toast('金额格式不对')
                  return ''
                }
                return value
              }
            },
            {
              uuId: randomId(),
              title: '上市日期',
              flag: 'ttm',
              show: false,
              type: 'monthrange',
              selected: true,
              value1: dateRange?.rawValue1 || '',
              value2: dateRange?.rawValue2 || '',
              rawValue1: dateRange?.rawValue1 || '',
              rawValue2: dateRange?.rawValue2 || '',
              placeholder1: '',
              placeholder2: ''
            }
          ]
          this.rawFilterData = [...sortPriceRaw, ...filterData]
          this.updateFilterData([...sortPriceRaw, ...filterData])
          // 处理默认项
          for (const f of filterData) {
            if (f.relevanceItemIndex && f.relevanceItemIndex.length > 0) {
              f.relevanceItemIndex.forEach(index => {
                const selected = f.children.some(e => e.selected)
                this.$store.commit('nav/updateRelevanceItemShow', { index, selected })
                // if (!selected) {
                //   this.cancelSelectedAll(this.filterData[index].children || [])
                // }
              })
            }
          }
        }
      })
    },
    // 获取默认模板
    async getTemplate() {
      return await getDefaultTemplateIdfunction().then(res => {
        this.defaultTemplateId = res.msg
        return res.msg
      })
    },
    resetData() {
      this.list = []
    },
    clickHandle(g) {
      this.$router.push({ name: 'FinishedDetail', params: { spuId: g.productId, skuId: g.skuId }})
    },
    getSellingPoints(item) {
      const list = item.solrProductDTOS || []
      const obj = list.find(v => v.skuId === item.skuId)
      return (obj && obj.sellingPoints) || []
    }
  }
}
</script>
<style lang="less">
.product{
}
</style>
